package cn.assumejson.springframework.aop.aspectj;

import cn.assumejson.springframework.aop.framework.AdvisedSupport;
import org.aopalliance.intercept.MethodInterceptor;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * JDK实现
 *
 * @author Mr. Li
 * @version 1.0
 * @since 1.0 2021/12/2 13:58
 */
public class JdkDynamicAopProxy implements AopProxy, InvocationHandler {

    private final AdvisedSupport advised;

    public JdkDynamicAopProxy(AdvisedSupport advised) {
        this.advised = advised;
    }

    @Override
    public Object getProxy() {
        return Proxy.newProxyInstance(this.getClass().getClassLoader(),
                advised.getTargetSource().getTarget().getClass().getInterfaces(),
                this);
    }

    @Override
    public AdvisedSupport getAdvised() {
        return this.advised;
    }

    // 动态代理出现死循环，循环调用 public boolean java.lang.Object.equals(java.lang.Object)
    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // 判断是否为切面
        if (advised.getMethodMatcher().matches(method, advised.getTargetSource().getTarget().getClass())) {
            MethodInterceptor methodInterceptor = advised.getMethodInterceptor();
            return methodInterceptor.invoke(
                    new ReflectiveMethodInvocation(advised.getTargetSource().getTarget(), method, args));
        }
        return method.invoke(advised.getTargetSource().getTarget(), args);
    }
}
